//importing javascipt core modules
Components.utils.import("resource://downloadextender/common.js");
Components.utils.import("resource://downloadextender/downloadextender.js");

if ("undefined" == typeof(downloadextender)) {
  var downloadextender = {};
};

downloadextender.filter = {  
  onnew: function() {
    try {
	  let cell_enabled = document.createElement("treecell");
      let cell_description  = document.createElement("treecell");
      let cell_contenttype = document.createElement("treecell");
      let cell_targetdirectory = document.createElement("treecell");

      cell_enabled.setAttribute("value", "false");		 
      cell_description.setAttribute("label", "My description");
      cell_contenttype.setAttribute("label", "My content");
	  //gives default download directory of Firefox for initial filter
      cell_targetdirectory.setAttribute("label", downloadextender.downloaddir().path); 

      let row = document.createElement("treerow");
      row.appendChild(cell_enabled);
      row.appendChild(cell_description);
      row.appendChild(cell_contenttype);
      row.appendChild(cell_targetdirectory);

      let item = document.createElement("treeitem");
      item.appendChild(row);
      document.getElementById("downloadextenderfiltertreechildren").appendChild(item);
	  //get tree
	  let tree = document.getElementById("downloadextenderfilterTable");
	  let treeView = tree.treeBoxObject.view;
	  //selects the newly created row 
	  tree.view.selection.select(treeView.rowCount-1);
	  //shows information in detail groupbox
	  downloadextender.filter.onselect();
	}
	catch (e) { downloadextender.consoleService("onnew: "+e); }
  },
  onremove: function() {
    try {
	  //get tree
	  let tree = document.getElementById("downloadextenderfilterTable");
	  if (tree.treeBoxObject.view.rowCount > 0) { 
	  //gets selected view from row
	  let view = tree.view;
      let selection = view.selection;
	  //gets index of currently selected row
	  let selindex = selection.currentIndex;
	  
	  //checks if row is selected, is so, do something
	  if (selindex > -1) {
	    //gets treeitem of currently selected row
	    let treeItem = view.getItemAtIndex(selindex);
	    //remove treeitem of tree 
	    treeItem.parentNode.removeChild(treeItem);
	    //selects the first row
	    tree.view.selection.select(0);
	    //shows information in detail groupbox
	    downloadextender.filter.onselect(); 
	  }
	  }
	}
	catch (e) { downloadextender.consoleService("onremove: "+e); }
  },
  onload: function() {
    try  {
	   //loads filters
	   let filters = downloadextender.pref.filters;	
	   //fill tree with filters
       for(var i in filters) {
	     let filter = filters[i];	
         let cell_enabled = document.createElement("treecell");
         let cell_description  = document.createElement("treecell");
         let cell_contenttype = document.createElement("treecell");
         let cell_targetdirectory = document.createElement("treecell");


         cell_enabled.setAttribute("value", unescape(filter["enabled"]));
         cell_enabled.setAttribute("label", i);			 
         cell_description.setAttribute("label", unescape(filter["description"]));
         cell_contenttype.setAttribute("label", unescape(filter["contenttype"]));
         cell_targetdirectory.setAttribute("label", unescape(filter["targetdirectory"])); 

         let row = document.createElement("treerow");
         row.appendChild(cell_enabled);
         row.appendChild(cell_description);
         row.appendChild(cell_contenttype);
         row.appendChild(cell_targetdirectory);

         let item = document.createElement("treeitem");
         item.appendChild(row);
         document.getElementById("downloadextenderfiltertreechildren").appendChild(item);	
	   }
	}
	catch (e) { downloadextender.consoleService("onload: "+e); }
  },  
  onselect : function() { 
    try { 
	  //get tree
	  let tree = document.getElementById("downloadextenderfilterTable");
	  //checks if there are rows present
	  if (tree.treeBoxObject.view.rowCount > 0) { 
	  //gets selected view from row
      //let selection = tree.view.selection;
	  //gets text from attributes of row 
      let cellValuechecked = tree.view.getCellValue(tree.currentIndex, tree.columns.getColumnAt(0));
	  let cellTextdescription = tree.view.getCellText(tree.currentIndex, tree.columns.getColumnAt(1));
	  let cellTextcontenttype = tree.view.getCellText(tree.currentIndex, tree.columns.getColumnAt(2));
	  let cellTexttargetdirectory = tree.view.getCellText(tree.currentIndex, tree.columns.getColumnAt(3));  	  
	     
      //show information in groupbox of filter window
      document.getElementById("downloadextenderfilterenableCheck").setAttribute("checked", cellValuechecked);
	  document.getElementById("downloadextenderfilterdescription").value = cellTextdescription;
	  document.getElementById("downloadextenderfiltercontent").value = cellTextcontenttype;
	  document.getElementById("downloadextendertargetdirectorytext").setAttribute("value", cellTexttargetdirectory);   
	  }
	}
    catch (e) { downloadextender.consoleService("onselect: "+e); }
  },
  ondefault : function() {
    try {
	  //load default filters 
	  let defaultfilters = downloadextender.pref.defaultfilters;
	  // Removing all children from an element (clears tree)
      let element = document.getElementById("downloadextenderfiltertreechildren");
      while (element.firstChild) {
        element.removeChild(element.firstChild);
      }
	  //makes rows for tree from defaultfilters
	  for(var i in defaultfilters) {
	    let defaultfilter = defaultfilters[i];	
        let cell_enabled = document.createElement("treecell");
        let cell_description  = document.createElement("treecell");
        let cell_contenttype = document.createElement("treecell");
        let cell_targetdirectory = document.createElement("treecell");

        cell_enabled.setAttribute("value", unescape(defaultfilter["enabled"]));
        cell_enabled.setAttribute("label", i);			 
        cell_description.setAttribute("label", unescape(defaultfilter["description"]));
        cell_contenttype.setAttribute("label", unescape(defaultfilter["contenttype"]));
        cell_targetdirectory.setAttribute("label", unescape(defaultfilter["targetdirectory"])); 

        let row = document.createElement("treerow");
        row.appendChild(cell_enabled);
        row.appendChild(cell_description);
        row.appendChild(cell_contenttype);
        row.appendChild(cell_targetdirectory);
		
        let item = document.createElement("treeitem");
        item.appendChild(row);
        document.getElementById("downloadextenderfiltertreechildren").appendChild(item);	
	  }
	  //gets the tree
	  let tree = document.getElementById("downloadextenderfilterTable");
      
	  //checks if there are rows present
	  if (tree.treeBoxObject.view.rowCount > 0) { 
	  //selects the first row
	  tree.view.selection.select(0);
	  //shows information in detail groupbox
	  downloadextender.filter.onselect(); 
	  }
	}
	catch (e) { downloadextender.consoleService("ondefault: "+e); }
  },  
  onbrowse : function() {
    try  {	

      let choosedir = downloadextender.getlocalisedstring("prefwindow.properties", "downloadextender_choosetargetdirectory"); 
	  let filepicker = downloadextender.fp();
	  let nsilocalfile = downloadextender.nsilocalfile();
	  let downloaddir = downloadextender.downloaddir().path;
	  
	  let ruletargetdirectory = document.getElementById("downloadextendertargetdirectorytext").getAttribute("value");
	  if (ruletargetdirectory == "" || ruletargetdirectory==null) 	    
	  ruletargetdirectory = downloaddir;  	  	
	  nsilocalfile.initWithPath(ruletargetdirectory);
	  
      if( !nsilocalfile.exists() || !nsilocalfile.isDirectory())	 
	   nsilocalfile.initWithPath(downloaddir);	  
	  
	  filepicker.init(window, choosedir, filepicker.modeGetFolder);	 	  
	  filepicker.displayDirectory = nsilocalfile; 
	  
      if (filepicker.show() == 0)  {  
	    document.getElementById("downloadextendertargetdirectorytext").setAttribute("value", filepicker.file.path);
        let newpath = filepicker.file.path;	
		let tree = document.getElementById("downloadextenderfilterTable");	 	   
	    //gets selected view from row
        let selection = tree.view.selection;	  
        //sets the picked directory into three
	    tree.view.setCellText(tree.currentIndex, tree.columns.getColumnAt(3),newpath); 
      }	
	}
    catch (e) { downloadextender.consoleService("onbrowse: "+e); }
  },
  onchangetarget: function(text) {
    try {
	  //gets the tree
	  let tree = document.getElementById("downloadextenderfilterTable");	 	   
	  //gets selected view from row
      let selection = tree.view.selection;	  
      //sets the changed target directory into tree	  
	  tree.view.setCellText(tree.currentIndex, tree.columns.getColumnAt(3),text.value); 	  
	}
	catch (e) { downloadextender.consoleService("onchangetarget: "+e); }
  },
  onchangedescription: function(text) {
    try {
	  //gets the tree
	  let tree = document.getElementById("downloadextenderfilterTable");	 	   
	  //gets selected view from row
      let selection = tree.view.selection;	  
      //sets the changed description into tree	  
	  tree.view.setCellText(tree.currentIndex, tree.columns.getColumnAt(1),text.value); 
	}
	catch (e) { downloadextender.consoleService("onchangedescription: "+e); }
  },
  onchangecontent: function(text) {
    try {
	  //gets the tree
	  let tree = document.getElementById("downloadextenderfilterTable");	 	   
	  //gets selected view from row
      let selection = tree.view.selection;	  
      //sets the changed contenttype into tree
	  tree.view.setCellText(tree.currentIndex, tree.columns.getColumnAt(2),text.value); 
	}
	catch (e) { downloadextender.consoleService("onchangecontent: "+e); }
  },
  onexport: function() {
    try {
      let exportheader = downloadextender.getlocalisedstring("prefwindow.properties", "downloadextender_export_filters");
      let exportfilters = [];
	  let filters = downloadextender.pref.filters;	
	  let jsonstring = JSON.stringify(filters);

      let nsIFilePicker = Components.interfaces.nsIFilePicker;
      let fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
      fp.init(window, exportheader, nsIFilePicker.modeSave);
      fp.defaultString = "Filters.json";
      fp.appendFilter("JSON files (*.json)","*.json");
      fp.defaultExtension = ".json";
      let res = fp.show();
      if (res == nsIFilePicker.returnOK || res == nsIFilePicker.returnReplace) {
        let outputStream = Components.classes["@mozilla.org/network/file-output-stream;1"]
            .createInstance(Components.interfaces.nsIFileOutputStream);
        outputStream.init( fp.file, 0x02 | 0x08| 0x20,0777, 0 );
        let result = outputStream.write(jsonstring, jsonstring.length);
        outputStream.close();
        }
	}
	catch (e) { downloadextender.consoleService("filter onexport: "+e); }
  },
  onimport: function() {
    try {
	  let promptservice = downloadextender.promptservice();
      let importheader = downloadextender.getlocalisedstring("prefwindow.properties", "downloadextender_import_filters");
      let importquestion =  downloadextender.getlocalisedstring("prefwindow.properties", "downloadextender_import_filtersquestion");
	  let importcheck =  downloadextender.getlocalisedstring("prefwindow.properties", "downloadextender_detectall_check");
      let check = {value: false};
      let result = promptservice.confirmCheck(null, importheader, importquestion,importcheck, check);
      if(check.value) {
        let nsIFilePicker = Components.interfaces.nsIFilePicker;
        let fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
        fp.init(window, importheader, nsIFilePicker.modeOpen);
        fp.appendFilter("JSON files (*.json)","*.json");
        let res = fp.show();
        if (res == nsIFilePicker.returnOK) {
          let inputFile = Components.classes["@mozilla.org/network/file-input-stream;1"].createInstance(Components.interfaces.nsIFileInputStream);
          let readInputStream = Components.classes["@mozilla.org/scriptableinputstream;1"].createInstance(Components.interfaces.nsIScriptableInputStream);
          inputFile.init(fp.file, 0x01, 444, 0);
          readInputStream.init(inputFile);
          let data = readInputStream.read(-1);
          var importfilters = JSON.parse(data);
		  var imported = "ok";
		}
	  }  
	  
	  if (imported == "ok") {
	  
	  // Removing all children from an element (clears tree)
      let element = document.getElementById("downloadextenderfiltertreechildren");
      while (element.firstChild) {
        element.removeChild(element.firstChild);
      }	
	
      //import filters
	  let filters = importfilters;	
	  //fill tree with filters
      for(var i in filters) {
	  let filter = filters[i];	
      let cell_enabled = document.createElement("treecell");
      let cell_description  = document.createElement("treecell");
      let cell_contenttype = document.createElement("treecell");
      let cell_targetdirectory = document.createElement("treecell");


      cell_enabled.setAttribute("value", unescape(filter["enabled"]));
      cell_enabled.setAttribute("label", i);			 
      cell_description.setAttribute("label", unescape(filter["description"]));
      cell_contenttype.setAttribute("label", unescape(filter["contenttype"]));
      cell_targetdirectory.setAttribute("label", unescape(filter["targetdirectory"])); 

      let row = document.createElement("treerow");
      row.appendChild(cell_enabled);
      row.appendChild(cell_description);
      row.appendChild(cell_contenttype);
      row.appendChild(cell_targetdirectory);

      let item = document.createElement("treeitem");
      item.appendChild(row);
      document.getElementById("downloadextenderfiltertreechildren").appendChild(item);   
	  }
      }	  
	}
	catch (e) { downloadextender.consoleService("filter onimport: "+e); }
  },
  onchangeenable: function(boolenable) {
    try {
	  //gets the tree
	  let tree = document.getElementById("downloadextenderfilterTable");	 	   
	  //gets selected view from row
      let selection = tree.view.selection;	  
      //sets the changed checkbox into three
	  tree.view.setCellValue(tree.currentIndex, tree.columns.getColumnAt(0),!boolenable.checked); 
	}
	catch (e) { downloadextender.consoleService("onchangeenable: "+e); }
  }  
};
